$(() => {
  // 监听消息传递
  chrome.extension.onMessage.addListener(
    function (req, sender, res) {
      if (req.action === 'completed') {
        //页面加载完毕
        if (/^https:\/\/item\.taobao\.com\/item.htm/.test(req.url)){
          $('html,body').animate({ scrollTop: document.body.scrollHeight }, 1000)
          setTimeout(() => {
            getDetail(req)
          }, 1000)
        } else if(/^https:\/\/.+\.taobao\.com\/.+\.htm/.test(req.url)){
          window.scrollTo(0, document.body.scrollHeight)
          getList(req, res)
        }
      }
      // 一定要 return
      return true
    }
  )
})


// 获取商品列表以及sku
function getList() {
  if (/^https:\/\/.+\.taobao\.com\/.+\.htm/.test(location.href)) {
    console.log('获取列表信息')
    var productList = []
    var item = $('.shop-hesper-bd .item')
    let timer = setInterval(function() {
      if (item.length > 0) {
        clearInterval(timer)
        item.each(function() {
          if (productList.length > 0) {
            let flag = true
            productList.forEach(product => {
              if ('taobao_' + $(this).attr('data-id') === product[0].id) flag = false
            })
            flag ? productList.push([{ id: 'taobao_' + $(this).attr('data-id'), url: $(this).find('.photo a').attr('href') }]) : null
          } else {
            productList.push([{ id: 'taobao_' + $(this).attr('data-id'), url: $(this).find('.photo a').attr('href') }])
          }
        })
        
        // 判断是否有分页组件 没有则end
        var pagination = $('.shop-hesper-bd>.pagination a')
        if (pagination && pagination.length > 0) {
          if ($(pagination[pagination.length - 1]).attr('class') === 'disable') {
            // 最后一页
            sendMsg({ data: productList }, 'end')
          } else {
            sendMsg({ data: productList, url: $(pagination[pagination.length - 1]).attr('href') }, 'next')
          }
        } else {
          sendMsg({ data: productList }, 'end')
        }
      }
    }, 1000)
  }
}

var detailInfo = new Object()

// 获取sku数据
function getDetail() {
  if (/^https:\/\/item\.taobao\.com\/item.htm/.test(location.href)) {
    // 主图
    detailInfo.images = []
    let scrollImages = $('#J_UlThumb li')
    if(scrollImages.length > 0) {
      scrollImages.each(function(i) {
        if (detailInfo.images.length < 5 && $(this).attr('id') !== 'J_VideoThumb') {
          detailInfo.images.push({ imageURL: $(this).find('img').attr('src').replace('50x50', '430x430').replace('_.webp', ''), isMain: detailInfo.images.length === 0 ? true : false , sort: i, streamMediaType: 'IMG'})
        }
      })
    }
    console.log('获取淘宝商品详情')
    try {
      detailInfo.weight = 1 //重量
      detailInfo.title = $('#J_Title .tb-main-title').attr('data-title') // 标题
      detailInfo.productSourceType = '4' // 来源

      // 品牌
      $('#attributes .attributes-list li').each(function() {
        if ($(this).text().indexOf('品牌') !== -1) {
          detailInfo.brand = $(this).attr('title')
        }
      })
      if (!detailInfo.brand) detailInfo.brand = '无'

      // 报价
      var skuOuterHTML = $('#J_sidebar_config').next('script')[0].outerHTML.trim().split(`Hub.config.set('sku',`)[1].split(`Hub.config.set('desc'`)[0].trim().split('});')[0].trim().split('valItemInfo')[1].trim() 
      if (skuOuterHTML.indexOf('skuMap') !== -1) {
        // 按规格
        detailInfo.specifications = []
        detailInfo.productSpecifications = []

        let valItemInfo = skuOuterHTML.split('skuMap')[1].trim().split(',propertyMemoMap:')
        let skuMap = JSON.parse(valItemInfo[0].trim().substr(1).trim())
        detailInfo.quoteMode = 'SPECIFICATIONS'
        let skuList = []
        $('#J_isku .tb-skin>dl.J_Prop ul.J_TSaleProp').each(function(){
          let name = $(this).attr('data-property')
          let values = []
          $(this).find('li').each(function() {
            let a = $(this).find('a')
            let icon = ''
            if (a.attr('style') && a.attr('style').indexOf('background:url') !== -1) {
              icon = a.attr('style').split('background:url(')[1].split(')')[0]
            }
            values.push({ icon: icon, value: a.text().trim() })
            skuList.push({ key: $(this).attr('data-value'), value: a.text().trim()})
          })
          detailInfo.specifications.push({ name: name, values: values })
        })
        for (let i in skuMap) {
          let nameList = i.split(';').filter(v => v)
          let names = [], value = [], obj = {}
          nameList.forEach((v, index) => {
            let skuName = skuNameFilter(v, skuList)
            if (skuName) {
              names.push(skuName)
              obj['name' + index] = skuName
            }
          })
          if (names.length > 0) {
            value = names.join(',')
            detailInfo.productSpecifications.push({ names: names, value: value, ...obj, sellingPrice: skuMap[i].price, distributionAmount: 0 })
          }
        }
      } else {
        // 按数量
        detailInfo.quoteMode = 'NUMBERS'
        detailInfo.numbersQuote = {}
        detailInfo.numbersQuote.inventory = $('#J_SpanStock').text().trim()
        detailInfo.numbersQuote.numbersQuotes = [{ startNumber: 1, price: $('#J_StrPrice .tb-rmb-num').text().trim() }]
      }

      // 商品规格详情介绍
      let parameterList = []
      $('#attributes .attributes-list li').each(function(i) {
        parameterList.push($(this).text())
      })
      detailInfo.productSourceInfo = {
        url:location.href,
        title: detailInfo.title,
        name: '产品参数',
        props: parameterList,
        specs: []
      }

      // 详情图片
      let timer = setInterval(function() {
        if ($('#J_DivItemDesc').text().trim() !== '描述加载中') {
          let html = $('#J_DivItemDesc')
          html.find('table').remove()

          html.find('img').each(function() {
            let lazyload = $(this).attr('data-ks-lazyload')
            if (lazyload) {
              $(this).attr('src', lazyload)
            }
          })
          detailInfo.info = html.html()
          clearInterval(timer)
          sendMsg(detailInfo, 'upload')
        }
      },1000)
    }
    catch(error) {
      console.log('获取详情失败---->>>>' + error)
    }

  }
}

function skuNameFilter(key, list) {
  for (let i in list) {
    if (key === list[i].key) return list[i].value
  }
}

// 将获取内容传递给后台脚本进行处理
function sendMsg(msg, cmd) {
  chrome.extension.sendMessage({ 'msg': msg, 'cmd': cmd })
}
